/*
 * Coding by Zhonghua. from 18-9-18 下午3:44.
 */

package vip.inode.demo.opusaudiodemo.utils

import android.os.Environment
import android.util.Log
import vip.inode.demo.opusaudiodemo.presenter.DecodeOpusPresenter
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.OutputStream
import java.io.RandomAccessFile
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.text.SimpleDateFormat
import java.util.Date
import kotlin.experimental.and

object Uilts {
    fun byteArrayToShortArray(byteArray: ByteArray): ShortArray {
        val shortArray = ShortArray(byteArray.size / 2)
        ByteBuffer.wrap(byteArray).order(ByteOrder.nativeOrder()).asShortBuffer().get(shortArray)
        return shortArray
    }

    fun shortArrayToByteArray(shortArray: ShortArray): ByteArray {
        val count = shortArray.size
        val dest = ByteArray(count shl 1)
        for (i in 0 until count) {
            dest[i * 2] = ((shortArray[i] and 0xFFFF.toShort()).toLong() shr 0).toByte()
            dest[i * 2 + 1] = ((shortArray[i] and 0xFFFF.toShort()).toLong() shr 8).toByte()
        }
        return dest
    }


    /********************test**********************/
    private var OPUS_AUDIO_PATH: String?
        //call-10086.opus
//          get() = File(Environment.getExternalStorageDirectory().toString(), "test_audio.opus").path
        get() = File(Environment.getExternalStorageDirectory().toString(), "test_1_opus.ops").path
//    get() = File(Environment.getExternalStorageDirectory().toString(), "call-10086.opus").path
        set(value) = TODO()

    fun testOpusFileDecoder() {
        val tntOpusUtils = OpusUtils.getInstant()
        val decoderHandler = tntOpusUtils.createDecoder(
            DecodeOpusPresenter.DEFAULT_AUDIO_SAMPLE_RATE,
            DecodeOpusPresenter.DEFAULT_OPUS_CHANNEL)

        val extStorageDirectory = Environment.getExternalStorageDirectory().toString()
        val file =
            File(extStorageDirectory, "test_1_opus_to_pcm" + ".pcm") //创建文件，第一个参数为路径，第二个参数为文件名
        var outStream: OutputStream? = null
        outStream = FileOutputStream(file) //创建输入流
        val out = BufferedOutputStream(outStream)

        val fis: FileInputStream
        try {
            fis = FileInputStream(OPUS_AUDIO_PATH)
        } catch (e: Exception) {
            return
        }

        val bis = BufferedInputStream(fis)
        while (true) {
            val bufferArray = ByteArray( DecodeOpusPresenter.BUFFER_LENGTH )
            var read: Int = -1
            try {
                read = bis.read(bufferArray, 0, bufferArray.size)
            } catch (e: Exception) {

            }

            if (read < 0) {//已经读完了
                Log.i("DecodeOpusPresenter.TAG", "OpusFileDecoder compare")
                break
            } else {
                val decodeBufferArray = ShortArray(bufferArray.size * 4)
                val size = tntOpusUtils.decode(decoderHandler, bufferArray, decodeBufferArray)
                if (size > 0) {
                    val decodeArray = ShortArray(size)
                    System.arraycopy(decodeBufferArray, 0, decodeArray, 0, size)

//                        opusDecode(decodeArray)//输出数据到接口
                    out.write(shortArrayToByteArray(decodeArray))
                } else {
                    Log.e("DecodeOpusPresenter.TAG", "opusDecode error : $size")
                    break
                }
            }

        }
        ConvertUtils.convertPcm2Wav(file.path, file.path)
        tntOpusUtils.destroyDecoder(decoderHandler)
        bis.close()
        fis.close()
    }
}